package com.dldata.devtools30.controller.sysform;

import com.dldata.devtools30.entity.DevtFormFieldcheckEntity;
import com.dldata.devtools30.repository.common.DlBaseJdbcTemplate;
import com.dldata.devtools30.repository.sysform.DevtFormFieldCheckDao;
import com.dldata.devtools30.utils.DlScriptEngine;
import com.dldata.devtools30.utils.Public;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhw on 2020-08-27.
 */
@Controller
@RequestMapping(value = "/DevtFormListTemplateSqlCheckController")
public class DevtFormListTemplateSqlCheckController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    DevtFormFieldCheckDao sysFormFieldCheckDao;
    @Autowired
    private DlBaseJdbcTemplate jdbcTemplate;
    
    @RequestMapping(value = "/getdata")
    @ResponseBody
    public Result getOne(String id, @RequestParam Map<String, String> paramMap) throws IOException {
        
        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        List<Map> dataList= new LinkedList<>();
        try {
            
            DevtFormFieldcheckEntity customTypeEntityList = sysFormFieldCheckDao.findById(id).orElse(null);
            if(customTypeEntityList==null){
                return Result.error("未找到数据");
            }
            
            
            return Result.ok(customTypeEntityList);
            
        }catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".getAll() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }
        
    }
    
    @RequestMapping(value = "/getAllByPid")
    @ResponseBody
    public Result getallByPid(String pid,@RequestParam Map<String, String> paramMap) throws IOException {
        
        String search=paramMap.get("search");
        List<Map> dataList= new LinkedList<>();
        try {
            search=search==null?"":search;
            search="%"+search+"%";
            List <DevtFormFieldcheckEntity> customTypeEntityList = sysFormFieldCheckDao.getAllFormFieldCheck(search, pid);
            
            for (int i = 0; i < customTypeEntityList.size(); i++) {
//                    "校验名称,激活,错误消息提示,说明
                DevtFormFieldcheckEntity pFunctionconfigformEntity = customTypeEntityList.get(i);
                Map<String,Object> data= new HashMap<>();
                data.put("name",pFunctionconfigformEntity.getName());
                data.put("active",pFunctionconfigformEntity.getActive()!=null&&pFunctionconfigformEntity.getActive()==1?"是":"否");
                data.put("errorinfo",pFunctionconfigformEntity.getErrorinfo());
                data.put("fieldcode",pFunctionconfigformEntity.getFieldcode());
                data.put("checktype",pFunctionconfigformEntity.getChecktype());
                data.put("id",pFunctionconfigformEntity.getId());
                data.put("bz",pFunctionconfigformEntity.getBz());
                
                dataList.add(data);
                
            }
            return Result.ok(dataList);
            
        }catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".getAll() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }
        
    }
    
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(
            String id,@RequestParam Map<String, String> paramMap) throws IOException {
        
        if(StringUtil.isEmptyOrLength0(id)){
            return Result.error("参数有误");
        }
        try {
            sysFormFieldCheckDao.deleteById(id);
            
            
            return Result.ok();
            
        }catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }
        
    }
    
    @RequestMapping(value = "/getCheckDemo")
    @ResponseBody
    public Result getCheckDemo(
            String search,@RequestParam Map<String, String> paramMap) throws IOException {
        
        search=search==null?"":search;
        LinkedList dataList= new LinkedList();
        
        SAXReader reader = new SAXReader();
        try {
            Document document= reader.read(this.getClass().getResourceAsStream("/validatedata.xml"));
            List<Element> elements= document.getRootElement().elements("validateitem");
            for (int i = 0; i < elements.size(); i++) {
                Element element = elements.get(i);
                HashMap dataMap=new HashMap();
                dataMap.put("name",element.attributeValue("name",""));
                dataMap.put("errorinfo",element.attributeValue("errorinfo",""));
                dataMap.put("content",element.getText().replaceAll("\\\\t","").replaceAll("            ",""));
                dataList.add(dataMap);
            }
            return Result.ok(dataList);
            
        }catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }
        
    }
    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(
            String subid, @RequestParam Map<String, String> paramMap, DevtFormFieldcheckEntity entity) throws IOException {
        
        if(StringUtil.isEmptyOrLength0(entity.getName()) ){
            return Result.error("名称不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getContent())){
            return Result.error("验证内容不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getErrorinfo())){
            return Result.error("提示内容不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getChecktype())){
            return Result.error("类型不能为空");
        }
        try {
            
            Pattern pattern = Pattern.compile(Public.REG_FIELD_ZH);
            Matcher matcher1=pattern.matcher("//[测试主表Demo.名称] !=null;");
            logger.debug(matcher1.find() + "");
            
            String sysCrfFormFieldEntityContent = entity.getContent();
            Matcher matcher=pattern.matcher(sysCrfFormFieldEntityContent);
            StringBuilder fieldCode=new StringBuilder();
            while(matcher.find()){
                String groupValues = matcher.group();
                logger.debug("[" + groupValues + "]");
                sysCrfFormFieldEntityContent=sysCrfFormFieldEntityContent.replace(groupValues, "111");
                fieldCode.append(groupValues);
                fieldCode.append(",");
            }
            if(fieldCode.length()>0){
                fieldCode.deleteCharAt(fieldCode.length()-1);
            }
            entity.setFieldcode(fieldCode.toString());
            
            if(!DlScriptEngine.testJavaScript(sysCrfFormFieldEntityContent)){
                return Result.error("脚本代码格式可能不正确");
            }
            
            if (entity.getId()==null||entity.getId().equals("")) {
                entity.setId(UUID.randomUUID().toString());
            }
            sysFormFieldCheckDao.save(entity);
            
            return Result.ok("保存成功");
            
        }catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }
        
    }
    
    @RequestMapping(value = "/saveSql")
    @ResponseBody
    public Result saveSql(
            String subid, @RequestParam Map<String, String> paramMap, DevtFormFieldcheckEntity entity) throws IOException {
        
        if(StringUtil.isEmptyOrLength0(entity.getName()) ){
            return Result.error("名称不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getContent())){
            return Result.error("验证内容不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getErrorinfo())){
            return Result.error("提示内容不能为空");
        }
        if(StringUtil.isEmptyOrLength0(entity.getChecktype())){
            return Result.error("类型不能为空");
        }
        try {
            
            Pattern pattern = Pattern.compile(Public.REG_FIELD_ZH);
            Matcher matcher1=pattern.matcher("//[测试主表Demo.名称] !=null;");
            logger.debug(matcher1.find() + "");
            
            String sysCrfFormFieldEntityContent = entity.getContent();
            Matcher matcher=pattern.matcher(sysCrfFormFieldEntityContent);
            StringBuilder fieldCode=new StringBuilder();
            while(matcher.find()){
                String groupValues = matcher.group();
                logger.debug("[" + groupValues + "]");
                sysCrfFormFieldEntityContent=sysCrfFormFieldEntityContent.replace(groupValues, "111");
                fieldCode.append(groupValues);
                fieldCode.append(",");
            }
            if(fieldCode.length()>0){
                fieldCode.deleteCharAt(fieldCode.length()-1);
            }
            entity.setFieldcode(fieldCode.toString());
            
            boolean testResult=false;
            try {
                jdbcTemplate.queryForList(sysCrfFormFieldEntityContent);
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                testResult=true;
                return Result.error("脚本代码格式可能不正确");
            }
            
            if (entity.getId()==null||entity.getId().equals("")) {
                entity.setId(UUID.randomUUID().toString());
            }
            sysFormFieldCheckDao.save(entity);
            
            return Result.ok("保存成功");
            
        }catch (Exception ex){
            logger.error("【执行"+this.getClass().getName()+".delete() 方法失败 】异常："+ex.getMessage(),ex);
            return Result.error("系统错误，请稍候再试！");
        }
        
    }
    
    
    
}
